package com.woniuxy.background.controller;

import com.github.pagehelper.PageInfo;
import com.woniuxy.background.advice.SysLog;
import com.woniuxy.background.common.RestResult;
import com.woniuxy.background.pojo.Log;
import com.woniuxy.background.service.LogService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/log")
public class LogController {

    @Autowired
    private LogService logService;

    @GetMapping("/list")
    @ResponseBody
    @RequiresPermissions("log:log:list")
    public RestResult list(@RequestParam(value = "page",defaultValue = "1",required = false) Integer currentPage,
                           @RequestParam(value = "limit",defaultValue = "5",required = false) Integer pageSize,
                           String username){

        List<Log> logs = logService.queryLogsByPage(currentPage,pageSize,username);
        PageInfo pageInfo = new PageInfo(logs);
        return RestResult.success(pageInfo);
    }

    @DeleteMapping("/deleteLog/{keys}")
    @ResponseBody
    @SysLog(value = "删除多个日志")
    @RequiresPermissions("log:log:delete")
    public RestResult deleteLog(@PathVariable("keys") String keys){
        String[] arr = keys.split(",");
        List<Integer> list = new ArrayList();
        for (String id : arr) {
            list.add(Integer.parseInt(id));
        }
        try {
            logService.batchDeleteLog(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success("删除成功");
    }

    @DeleteMapping("/delete/{logId}")
    @ResponseBody
    @SysLog(value = "删除日志")
    @RequiresPermissions("log:log:delete")
    public RestResult deleteLog(@PathVariable("logId")int logId){
        try {
            logService.deleteByPrimaryKey(logId);
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.failed("删除失败！");
        }
        return RestResult.success("删除成功！");
    }
}
